package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/students")
@CrossOrigin(originPatterns = "http://localhost:*")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    // 查询所有学生
    @GetMapping
    public Map<String, Object> findAll() {
        List<Student> students = studentService.findAll();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "查询成功");
        result.put("data", students);
        return result;
    }
    
    // 根据ID查询学生
    @GetMapping("/{id}")
    public Map<String, Object> findById(@PathVariable Long id) {
        Student student = studentService.findById(id);
        Map<String, Object> result = new HashMap<>();
        if (student != null) {
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", student);
        } else {
            result.put("code", 404);
            result.put("message", "学生不存在");
        }
        return result;
    }
    
    // 保存学生信息（新增或更新）
    @PostMapping
    public Map<String, Object> save(@RequestBody Student student) {
        boolean success = studentService.save(student);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "保存成功");
        } else {
            result.put("code", 500);
            result.put("message", "保存失败");
        }
        return result;
    }
    
    // 根据ID删除学生
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteById(@PathVariable Long id) {
        boolean success = studentService.deleteById(id);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "删除成功");
        } else {
            result.put("code", 500);
            result.put("message", "删除失败");
        }
        return result;
    }
    
    // 根据姓名模糊查询
    @GetMapping("/search")
    public Map<String, Object> findByName(@RequestParam String name) {
        List<Student> students = studentService.findByName(name);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "查询成功");
        result.put("data", students);
        return result;
    }
}